package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyThemeQueryObject;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class StrategyThemeServiceImpl implements IStrategyThemeService {
    @Autowired
    private StrategyThemeRepository repository;
    @Autowired
    private MongoTemplate template;
    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);//防止游标
        repository.save(strategyTheme);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        repository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public StrategyTheme get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {
    return repository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQueryObject qo) {
        //查询的条件对象
        Query query=new Query();
        //拼接条件
        long count = template.count(query, StrategyTheme.class);//计算一共有多少条数据 query 为无条件 totalCount  集合MOngoDb
        if (count==0){
        return Page.empty();//空的页面对象
        }
        //分页加排序---->条件拼接
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        //把条件放入查询对象中
        query.with(pageRequest);
        //查询当前结果集template.find
        List<StrategyTheme> list = template.find(query, StrategyTheme.class);
            //PageImpl等价于之前的PageResult
            return new PageImpl<>(list,pageRequest,count);//PageResult原生的  pageRequest当前页  多少条数
            //PageHadler  分页插件的
            }


    public void saveOrUpdate(StrategyTheme strategyTheme) {
        if (StringUtils.hasLength(strategyTheme.getId())) {
            repository.save(strategyTheme);
        } else {
            strategyTheme.setId(null);
            template.insert(strategyTheme);
        }
    }
}